package com.niiwoo.civet.account.listener;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.AccountRabbitConstant;
import com.niiwoo.civet.account.dto.request.RepaymentWithholdFailMsgMQDTO;
import com.niiwoo.civet.account.enums.RepayMsgTypeEnum;
import com.niiwoo.civet.account.service.local.MessageSendLocalService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消息发送监听器
 *
 * @author wuke
 * @create 2018-01-19 14:30
 **/
@Component
@Slf4j
public class MessageSendListener {

    @Autowired
    private MessageSendLocalService messageSendLocalService;

    /**
     * 还款相关消息发送
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {AccountRabbitConstant.Queue.REPAYMENT_MESSAGE_SEND})
    public void repaymentMessageSend(Message message, Channel channel) {
        String messageBody = null;
        try {
            messageBody = new String(message.getBody(), "UTF-8");
            log.info("还款相关MQ消息:{}", messageBody);
            RepayMsgTypeEnum repayMsgTypeEnum = JSON.parseObject(messageBody).getObject("repayMsgTypeEnum",RepayMsgTypeEnum.class);
            switch (repayMsgTypeEnum){
                case ACCOUNT_WITHHOLD_FAIL:
                    messageSendLocalService.accountWithholdFailMsgSend(JSON.parseObject(messageBody, RepaymentWithholdFailMsgMQDTO.class));
                    break;
                case CARD_WITHHOLD_FAIL:
                    messageSendLocalService.cardWithholdFailMsgSend(JSON.parseObject(messageBody, RepaymentWithholdFailMsgMQDTO.class));
                    break;
            }
        } catch (Exception e) {
            log.error("还款相关MQ消息消费异常:{}", messageBody,e);
        } finally {
            log.info("还款相关MQ消息ACK:{}", messageBody);
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("还款相关MQ消息basicAck异常,{}",messageBody,e);
            }
        }
    }

}
